package com.lunchspothack;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;

public class FacebookUtil {
	
	private static final String TAG = FacebookUtil.class.getSimpleName();
	
	private static final String PREF_SMARTKEY = "smartkey";
	
	public static List<Lunchspot> getCheckins(Context context) {
        // request
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		
        //FIXME:  Need to create a apigee user and get new smartkey from preferences//prefs.getString(PREF_SMARTKEY, null);
		String smartkey = "111111111"; //FIXME:  replace this placeholder with real smartkey
		
		List<Lunchspot> checkinSpots = new ArrayList<Lunchspot>();
		
		if (smartkey != null) {
			//FIXME:  replace app name, e.g. lunchspot
			String apigeeAppName = "realApiGeeAppName";
	        String jsonResponse = urlToString("https://" + apigeeAppName + "-api.apigee.com/v1/facebook/me/checkins?smartkey=" + smartkey);
	        Log.d(TAG, "Got JSon response " + jsonResponse);
	        if (jsonResponse != null) {
	            JSONObject jsonObject;
				try {
					jsonObject = new JSONObject(jsonResponse);
		            JSONArray checkinArray = jsonObject.getJSONArray("data");
		            
		            for(int i = 0; i < checkinArray.length(); i++) {
		            	JSONObject place = checkinArray.getJSONObject(i).getJSONObject("place");
		            	JSONObject location = place.getJSONObject("location");
		            	String name = place.getString("name");
		            	String latitude = location.getString("latitude");
		            	String longitude = location.getString("longitude");
		            	
		            	Log.e(TAG, "jsonobject:" + place.toString());
		            	
		            	checkinSpots.add(new Lunchspot(name, latitude, longitude));
		            }
		            
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					
					Log.e(TAG, "JSONException parsing for checkin info", e);
				}
	
	
	        }
		}
		
		return checkinSpots;
	}

    public static String urlToString(String url) /*throws Throwable*/ {
        HttpClient httpClient = new DefaultHttpClient();
        try {
            HttpGet request = new HttpGet(url);

            // sign the request
//            consumer.sign(request);

            HttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(instream));

                    StringBuilder builder = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }

                    return builder.toString();
                } catch (RuntimeException e) {
                    Log.e(TAG, "OAuth - retrieve email address error; RuntimeException on url=" + url, e);
                    request.abort();
                    throw new RuntimeException(e);
                } finally {
                    // Closing the input stream will trigger connection release
                    instream.close();
                }
            }
        } catch(ClientProtocolException e) {
        	Log.e(TAG, "ClientProtocolException in getting: " + url, e);
        } catch(IOException e) {
        	Log.e(TAG, "IOException in getting: " + url, e);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpClient.getConnectionManager().shutdown();
        }

        return null;
    }

	
}

